package com.company.cloud.user.modules.mgr.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.user.constant.ErrorUserEnum;
import com.company.cloud.user.constant.InviteCheckTypeEnum;
import com.company.cloud.user.constant.InviteStateTypeEnum;
import com.company.cloud.user.constant.InviteTypeEnum;
import com.company.cloud.user.modules.base.entity.*;
import com.company.cloud.user.modules.base.service.*;
import com.company.cloud.user.modules.cache.utils.UserConvertUtils;
import com.company.cloud.user.modules.mgr.controller.req.*;
import com.company.cloud.user.modules.mgr.service.TeamMgrService;
import com.company.cloud.user.modules.mgr.service.UserInvitationMgrService;
import com.company.common.server.config.cloud.ProjectConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Service
public class UserInvitationMgrServiceImpl implements UserInvitationMgrService {

	@Autowired
	private UserInvitationInfoService userInvitationInfoService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private ProjectConfig projectConfig;

	@Override
	@Transactional
	public void save(UserInvitationSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo user= AuthContextUtils.getUser();
		inviteCheck(params, user);
		UserInvitationInfo entity = UserConvertUtils.getUserInvitationInfo(params);
		entity.setCompanyNo(user.getCompanyNo());
		entity.setInvitationState(InviteStateTypeEnum.UNCONFIRMED.getCode());
		if (params.getOverDate() == null) {
			entity.setOverDate(LocalDateTime.now().plusDays(30));
		}
		if (InviteCheckTypeEnum.Password_Check.getCode().equals(params.getCheckType())) {
			entity.setCheckPassword(IdUtil.fastSimpleUUID());
		}
		entity.addCreateParam(user);
		entity.addEditParam(user);
		userInvitationInfoService.save(entity);
	}

	@Override
	@Transactional
	public void update(UserInvitationUpdateParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo user = AuthContextUtils.getUser();
		UserInvitationInfo entity = userInvitationInfoService.getById(params.getId());
		if (entity == null
				|| BaseConstant.EnabledEnum.ENABLED.getCode().equals(entity.getRowsState())
				|| InviteStateTypeEnum.CONFIRMED.getCode().equals(entity.getInvitationState())
				|| InviteStateTypeEnum.EXPIRED.getCode().equals(entity.getInvitationState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		entity = UserConvertUtils.getUserInvitationInfo(params, entity);
		entity.addEditParam(user);
		userInvitationInfoService.updateById(entity);
	}

	private void inviteCheck(UserInvitationSaveParam params, LoginSimpleUserInfo user) {
		if(projectConfig.isPlatformPattern()){ // 平台模式
			if (InviteTypeEnum.EMPLOYEE.getCode().equals(params.getInvitationType())) {
				params.setInvitationUserId(checkInvitationMobilePlat(params.getMobile())); // 验证手机号获取用户id
			} else {
				if (CheckUtils.hasInt(params.getInvitationUserId())) {
					UserInfo userInfo = userInfoService.getById(params.getInvitationUserId());
					if (!"PTC".equals(userInfo.getCompanyNo()) && !user.getCompanyNo().equals(userInfo.getCompanyNo())) {
						throw new BusinessException(ErrorUserEnum.Invitation_Fail);
					}
				} else {
					params.setInvitationUserId(checkInvitationMobilePlat(params.getMobile())); // 验证手机号获取用户id
				}
			}
		} else { // 公司模式
			if (InviteTypeEnum.EMPLOYEE.getCode().equals(params.getInvitationType())) {
				params.setInvitationUserId(checkInvitationMobileComp(params.getMobile(), user)); // 验证手机号获取用户id
			} else {
				if (CheckUtils.hasInt(params.getInvitationUserId())) {
					UserInfo userInfo = userInfoService.getById(params.getInvitationUserId());
					if (!user.getCompanyNo().equals(userInfo.getCompanyNo())) {
						throw new BusinessException(ErrorUserEnum.Invitation_Fail);
					}
				} else {
					params.setInvitationUserId(checkInvitationMobileComp(params.getMobile(), user)); // 验证手机号获取用户id
				}
			}
		}
	}

	/*验证手机号公司模式*/
	private Integer checkInvitationMobileComp(String mobile, LoginSimpleUserInfo user) {
		if (CheckUtils.isEmpty(mobile)) {
			throw new BusinessException(ErrorUserEnum.USER_MOBILE_NULL);
		}
		// 手机号重复邀请check
		List<UserInvitationInfo> oldEntityList = userInvitationInfoService.list(new QueryWrapper<UserInvitationInfo>()
				.eq("mobile", mobile)
				.eq("company_no", user.getCompanyNo())
				.eq("invitation_state", InviteStateTypeEnum.UNCONFIRMED.getCode())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
				.and(qw->qw.ge("over_date", LocalDateTime.now()).or().isNull("over_date"))
		);
		if (!CollectionUtils.isEmpty(oldEntityList)) {
			throw new BusinessException(BaseReturnEnum.DATA_EXISTS);
		}
		List<UserInfo> userInfoList =
				userInfoService.list(new QueryWrapper<UserInfo>()
						.eq("mobile", mobile)
						.eq("company_no", user.getCompanyNo())
				);
		if (!CollectionUtils.isEmpty(userInfoList)) {
			throw new BusinessException(ErrorUserEnum.USER_MOBILE_EXISTS);
		} else {
			return null;
		}
	}
	/*验证手机号平台模式*/
	private Integer checkInvitationMobilePlat(String mobile) {
		if (CheckUtils.isEmpty(mobile)) {
			throw new BusinessException(ErrorUserEnum.USER_MOBILE_NULL);
		}
		// 手机号重复邀请check
		List<UserInvitationInfo> oldEntityList = userInvitationInfoService.list(new QueryWrapper<UserInvitationInfo>()
				.eq("mobile", mobile)
				.eq("invitation_state", InviteStateTypeEnum.UNCONFIRMED.getCode())
				.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
				.and(qw->qw.ge("over_date", LocalDateTime.now()).or().isNull("over_date"))
		);
		if (!CollectionUtils.isEmpty(oldEntityList)) {
			throw new BusinessException(BaseReturnEnum.DATA_EXISTS);
		}
		List<UserInfo> userInfoList =
				userInfoService.list(new QueryWrapper<UserInfo>().eq("mobile", mobile));
		if (!CollectionUtils.isEmpty(userInfoList)) {
			if (userInfoList.size() > 1) { // 存在多条数据，不能创建
				throw new BusinessException(ErrorUserEnum.USER_MOBILE_EXISTS);
			}
			UserInfo userInfo = userInfoList.get(0);
			if (userInfo.getCompanyNo().equals("PTC")) { // 只能邀请PTC公司的人

				return userInfo.getId();
			} else {
				throw new BusinessException(ErrorUserEnum.USER_MOBILE_EXISTS);
			}
		} else {
			return null;
		}
	}
}
